<?php

namespace app\api\controller;

use addons\qrcode\Qrcode;
use app\admin\model\nursery\Attestation;
use app\admin\model\nursery\Companyattestation;
use app\common\controller\Api;
use app\common\helpers\ImageUtil;
use app\common\library\Auth;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\Invite;
use app\common\model\MoneyLog;
use app\common\model\user\Receive;
use app\common\model\Withdraw;
use app\common\model\WxData;
use fast\Random;
use think\Config;
use think\Db;
use think\Exception;
use think\Log;
use think\Validate;

/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['wxLogin','getWxPhone','follow'];
    protected $noNeedRight = '*';
    protected $model ='';
    public function _initialize()
    {
        parent::_initialize();

        $this->model=new \app\common\model\User();
        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }


    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar 头像地址
     * @param string $nickname 昵称
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $nickname = $this->request->post('nickname');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if (!$nickname && !$avatar) {
            $this->error('请上传头像或昵称');
        }
        if ($nickname) {
//            $exists = \app\common\model\User::where('nickname', $nickname)
//                ->where('id', '<>', $this->auth->id)->find();
//            if ($exists) {
//                $this->error(__('Nickname already exists'));
//            }
            $user->nickname = $nickname;
        }
        if($avatar){
            $user->avatar = $avatar;
        }
        $user->save();
        $this->success('修改成功');
    }


    /**
     * 用户登录
     * */
    public function wxLogin()
    {
        $validate = new \think\Validate([
            ['code', 'require', 'code不能为空'],
            ['avatar', 'require', '头像不能为空'],
            ['nickname', 'require', '昵称不能为空'],
            ['mobile', 'require', '电话号码不能为空'],
        ]);
        if (!$validate->check(input())) {
            $this->error('提交失败：' . $validate->getError());
        }
        $code = $this->request->param("code");
        $result = getOpenid($code);
        if (!isset($result['openid'])) {
            $this->error('请求错误', $result);
        }
        $data = [
            "nickname" => $this->request->param("nickname"),
            "avatar" => $this->request->param("avatar"),
            "username"=> $this->request->param("mobile"),
            "mobile"=> $this->request->param("mobile"),
        ];
        $ret = $this->auth->wx_login($data, $result['openid'], $result['session_key']);

        if ($ret) {
            $user = $this->auth->getUserinfo();
            $user2 = \app\common\model\User::get($user["id"]);
            $userinfo = [
                "id" => $user["id"],
                "nickname" => $user["nickname"],
                "avatar" => ImageUtil::handle($user["avatar"]),
                "status" => $user2["status"],
                "mobile" => $user["mobile"],
                "level" => $user2["level"],
                "is_certification" => $user2["is_certification"],
                "is_nursery_certification" => $user2["is_nursery_certification"],
                "token" => $user["token"],
                "is_bind_wechat_openid" => $user['wechat_openid'] ? 1 : 0
            ];
            $this->success(__('Logged in successful'), $userinfo);
        } else {
            $this->error($this->auth->getError());
        }
    }
    /**
     * 获取用户微信手机
     * @throws \think\Exception
     */
    public function getWxPhone()
    {
//        $user = $this->auth->getUser();
//        $tmp = getAccessToken();
//        $token = $tmp["access_token"];
//        $data['code'] = input('code');
//        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$token";
//        $info = \fast\Http::post($url,json_encode($data),'json');
//        // 一定要注意转json，否则汇报47001错误
//        $tmpinfo = json_decode($info,true);
//        if ($tmpinfo["errcode"]  == 0) {
//            $user_other=\app\common\model\User::where(["mobile"=>$tmpinfo["phone_info"]["purePhoneNumber"],"type_data"=>'0'])
//                ->where("id != ".$user["id"])->find();
//            if(!empty($user_other)) $this->error("该手机号已注册");
//            \app\common\model\User::where(["id"=>$user["id"]])->update(["mobile"=>$tmpinfo["phone_info"]["purePhoneNumber"]]);
//            $this->success('获取成功',$tmpinfo["phone_info"]["purePhoneNumber"]);
//        } else {
//            $this->error($tmpinfo["errcode"] );
//        }
        $tmp = getAccessToken();
        $token = $tmp["access_token"];
        $data['code'] = input('code');
        $url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=$token";
        $info = \fast\Http::post($url,json_encode($data),'json');
        // 一定要注意转json，否则汇报47001错误
        $tmpinfo = json_decode($info,true);
        if ($tmpinfo["errcode"]  == 0) {
            $this->success(__('Logged in successful'), ['mobile'=>$tmpinfo["phone_info"]["purePhoneNumber"]]);
        } else {
            $this->error($tmpinfo["errcode"] );
        }
    }

    /**
     * 获取设置
     * */
    public function getConfig()
    {
        $list["withdrawal_can_money"] = config("site.withdrawal_can_money");
        $list["withdrawal_explain"] = config("site.withdrawal_explain");
        $list["divide_ratio_site"] = config("site.divide_ratio_site");
        $list["profit_explain"] = config("site.profit_explain");
        $list["about_us"] = config("site.about_us");
        $list["receive_data"] = config("site.receive_data");
        $this->success("成功", $list);
    }

    /**
     * 绑定微信公众号
     */
    public function bindWechat(){
        $user = $this->auth->getUser();
        $wxCode = $this->request->param("wxCode");
        $result = getOpenid2($wxCode);
        if(isset($result['openid'])){
            $result2 = getWechatUserInfo($result['openid']);
            if(isset($result2['subscribe'])){
                $data = [
                    'wechat_openid'=> $result['openid'],
                    'is_follow' =>  $result2['subscribe'],
                    'follow_time' =>  isset($result2['subscribe_time']) ? $result2['subscribe_time'] : 0,
                ];
                \app\admin\model\User::update($data,['id'=>$user['id']]);
                $this->success("绑定成功");
            }
        }
        $this->error("绑定失败");
    }

    /**
     * 微信信息回调
     */
    public function follow(){
        $res = $this->checkSignaTure();
        if($res){
            $postObj = file_get_contents('php://input');
            $postArr = simplexml_load_string($postObj,'SimpleXMLElement',LIBXML_NOCDATA);
            if($postArr->MsgType == "event" && $postArr->Event && in_array($postArr->Event,['subscribe','unsubscribe'])){ //用户关注操作
                if($postArr->Event == "subscribe"){
                    $data =[
                        'is_follow'=>1,
                        'follow_time'=>$postArr->CreateTime,
                    ];
                }else{
                    $data =[
                        'is_follow'=>0,
                        'follow_time'=>null,
                    ];
                }
                \app\admin\model\User::update($data,['wechat_openid'=>$postArr->FromUserName]);
            }
            exit();
        }else{
            echo '';
            exit();
        }
    }


    /**
     * @return bool
     * 微信回调签名验证
     */
    private function checkSignaTure(){
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = "6lgV37Sz4QJHnozZpcdeleb";
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
        if($tmpStr == $signature){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 获取用户信息
     * */
    public function getUser()
    {
        $user = $this->auth->getUser();
        $info = \app\common\model\User::field("id,nickname,avatar,mobile,score,status,level,is_certification,is_nursery_certification")->where(["id" => $user["id"]])->find();

        if($info){
            $info['avatar_url'] =ImageUtil::handle($info['avatar']);
            $info['is_nursery_pay'] = 0;
            $authInfo =   Companyattestation::get(['user_id'=>$user['id']]);
            if($authInfo){
              $info['is_nursery_pay'] =$authInfo['is_pay'];
            }
            $Attestation = (new Attestation())->where(['user_id'=>$user['id']])->order('create_time desc')->find();

            $info['is_auth'] = 3; //已审核
            if($Attestation ){
                if($Attestation['status'] == '0' && $info['is_certification'] == '0'){
                    $info['is_auth'] = 1; //审核中
                }
                if($Attestation['status'] == '2' && $info['is_certification'] == '0'){
                    $info['is_auth'] = 2; //审核失败
                }
            }else{
                $info['is_auth'] = 0; ////没提交
            }
        }



        $this->success("成功", $info);
    }

    }



